import request, { ApiResponse } from './http';  // 导入封装后的请求函数
import { generateUUID } from './common';

import { BASE_URL } from '@/config'; // 导入基础 URL

// 用户信息类型定义
interface LoginResp {
  accessToken: string
  expiresTime: number
  openid: string
  refreshToken: string
  userId: string
}

// 更新用户信息类型定义以匹配实际返回的数据结构
interface UserProfile {
  id: number;
  nickname: string;
  avatar: string;
  mobile: string;
  sex: number;
  point: number;
  experience: number;
  level: string | null;
  brokerageEnabled: boolean | null;
}


/**
 * 注册
 * @returns 注册
 */
export const register = async (loginCode: string, phoneCode: string): Promise<ApiResponse<LoginResp>> => {
  try {
    const res = await request({
      url: '/member/auth/weixin-mini-app-login',
      method: 'POST',
      data: {
        loginCode, phoneCode, state: generateUUID()
      }
    });
    return res as ApiResponse<LoginResp>;
  } catch (err) {
    throw err;
  }
};

/**
 * 获取用户个人信息
 * @returns 用户信息
 */
export const getUserProfile = async (): Promise<ApiResponse<UserProfile>> => {
  try {
    const res = await request({
      url: '/member/user/get',
      method: 'GET'  // 修复：添加缺失的逗号
    });
    return res as ApiResponse<UserProfile>;
  } catch (err) {
    throw err;
  }
};

/**
 * 登出接口
 * @returns 登出结果
 */
export const logoutApi = async (): Promise<ApiResponse<any>> => {
  try {
    const res = await request({
      url: '/member/auth/logout',
      method: 'POST'
    });
    return res as ApiResponse<any>;
  } catch (err) {
    throw err;
  }
};


/**
 * 更新用户信息
 * @returns 用户信息
 */
export const modify = async (userProfile: UserProfile): Promise<ApiResponse<UserProfile>> => {
  try {
    const res = await request({
      url: '/member/user/update',
      method: 'PUT',
      data: userProfile
    });
    return res as ApiResponse<UserProfile>;
  } catch (err) {
    throw err;
  }
};

